package com.cloud.jdkTest;


import com.cloud.service.TargetService;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;


import java.lang.reflect.Method;

/**
 * cglib动态代理测试
 */
public class CGLIBProxy implements MethodInterceptor {

    //⽬目标类
    private Object targetObject;

    //绑定关系
    public Object newProxyInstance(Object targetObject){
        this.targetObject = targetObject;
        Enhancer enhancer = new Enhancer();
        //设置代理理类的父类（目标类）
        enhancer.setSuperclass(this.targetObject.getClass());
        //设置回调函数
        enhancer.setCallback(this);
        //创建⼦子类（代理理对象）
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {

        Object result = null;

        try {
            System.out.println("通过cglib动态代理来调用方法" + method.getName() + " before打印日志");
            result = methodProxy.invokeSuper(o, args);
            System.out.println("通过cglib动态代理来调用方法" + method.getName() + " after打印日志");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    public static void main(String[] args) {
        CGLIBProxy cglibProxy = new CGLIBProxy();
        TargetService proxyTargetService = (TargetService) cglibProxy.newProxyInstance(new TargetService());
        proxyTargetService.daBiz();
    }
}
